package uf.tax.laws.spider.gs;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uf.tax.laws.spider.HttpDAO;

public class GetLawList {
	HttpDAO dao;
	String type;

	public GetLawList(HttpDAO dao, String type) {
		this.dao = dao;
		this.type = type;
	}

	Pattern p = Pattern.compile(
			"<td bgcolor=\"#F0F0F0\" style=\"padding-left:15px\"><a href=\"\\.\\.(.*?)\" .*?>(.*?)</a>",
			Pattern.DOTALL);

	private int getTotalCount(String content) {
		Pattern _p = Pattern.compile("共(\\d+)项查询结果", Pattern.DOTALL);
		Matcher m = _p.matcher(content);
		if (m.find()) {
			return Integer.valueOf(m.group(1));
		}
		return 0;
	}

	public List<String> getLawList() {
		List<String> result = new ArrayList<String>();
		String content;
		try {
			String url = String.format(
					"http://hd.chinatax.gov.cn/guoshui/action/InitNewArticle.do?channelId=%d&&name=%s&&rtoken=fgk&cPage=%d",
					GetTypes.map.get(type), URLEncoder.encode(type, "utf-8"), 1);
			content = dao.get(url);
			int itemCount = getTotalCount(content);
			int pageIndex = 1;
			while (result.size() < itemCount) {
				if (pageIndex != 1) {
					url = String.format(
							"http://hd.chinatax.gov.cn/guoshui/action/InitNewArticle.do?channelId=%d&&name=%s&&rtoken=fgk&cPage=%d",
							GetTypes.map.get(type), URLEncoder.encode(type, "utf-8"), pageIndex);
					content = dao.get(url);
					Thread.sleep(100);
				}
				Matcher m = p.matcher(content);
				while (m.find()) {
					String u = m.group(1);
					result.add(u);
					System.out.println("match url: " + u);
				}
				pageIndex++;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}
